package com.ft.adbix.core.interactive;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;

public class EnhancedShakeDetector extends ShakeDetector {
    private static final int SHAKE_SLOP_TIME_MS = 500;
    private static final int SHAKE_COUNT_RESET_TIME_MS = 3000;

    private OnShakeListener onShakeListener;
    private int shakeCount = 0;
    private long lastShakeTime;
    private long firstShakeTime;

    public EnhancedShakeDetector(Context context) {
        super(context);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            long now = System.currentTimeMillis();

            if ((now - lastShakeTime) > SHAKE_SLOP_TIME_MS) {
                float acceleration = calculateAcceleration(event);
                
                if (acceleration > SHAKE_THRESHOLD) {
                    if (firstShakeTime == 0) {
                        firstShakeTime = now;
                        shakeCount = 0;
                    }

                    lastShakeTime = now;
                    shakeCount++;

                    if (onShakeListener != null) {
                        onShakeListener.onShake(shakeCount, acceleration);
                    }
                }
            }

            if ((now - firstShakeTime) > SHAKE_COUNT_RESET_TIME_MS) {
                resetShakeCount();
            }
        }
    }

    private float calculateAcceleration(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        return (float) Math.sqrt(
            Math.pow(x, 2) + 
            Math.pow(y, 2) + 
            Math.pow(z, 2)
        ) - SensorManager.GRAVITY_EARTH;
    }

    private void resetShakeCount() {
        shakeCount = 0;
        firstShakeTime = 0;
        lastShakeTime = 0;
    }

    public interface OnShakeListener {
        void onShake(int count, float strength);
    }
}